"""
-------------------------------------------------
    Author: Csm
    Date：2021-03-01 20:54
-------------------------------------------------
"""

"""
from channels.consumer import SyncConsumer, AsyncConsumer


class EchoConsumer(SyncConsumer):

    # 同步逻辑
    user = User.objects.get(username=username)

    def websocket_connent(self, event):
        self.send({
            "type": "websocket.accept"
        })

    def websocket_receive(self, event):
        self.send({
            "type": "websocket.send",
            "text": event["text"]
        })

class EchoAsyncConsumer(AsyncConsumer):

    # ORM变异步代码，方式一
    from channels.db import database_sync_to_async
    user = await database_sync_to_async(User.objects.get(username=username))

    # ORM变异步方式二
    @database_sync_to_async
    def get_username(username):
        return User.objects(username=username)

    async def websocket_connent(self, event):
        await self.send({
            "type": "websocket.accept"
        })

    async def websocket_receive(self, event):
        await self.send({
            "type": "websocket.send",
            "text": event["text"]
        })


# 什么时候使用sync或async?
# async内不能加sync代码
"""


"""
from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer

class MyConsumer(WebsocketConsumer):

    def connect(self):
        # 自定义的子协议
        self.accept(subprotocol="your protocol")
        # 拒绝连接
        self.close(code=403)

    def receive(self, text_data=None, bytes_data=None):
        self.send(text_data="imooc.com")
        self.send(bytes_data="imooc.com")
        self.close()

    def disconnect(self, code):
        pass


class MyAsyncConsumer(AsyncWebsocketConsumer):

    async def connect(self):
        # 自定义的子协议
        await self.accept(subprotocol="your protocol")
        # 拒绝连接
        await self.close(code=403)

    async def receive(self, text_data=None, bytes_data=None):
        await self.send(text_data="imooc.com")
        await self.send(bytes_data="imooc.com")
        await self.close()

    async def disconnect(self, code):
        pass
"""
